package top.zhdev.community.service.impl;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;
import top.zhdev.community.entity.DiscussPost;
import top.zhdev.community.mapper.DiscussPostMapper;
import top.zhdev.community.service.DiscussPostService;
import top.zhdev.community.utils.SensitiveFilter;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 帖子业务类
 */
@Service
public class DiscussPostServiceImpl implements DiscussPostService {

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    private DiscussPostMapper discussPostMapper;
    private SensitiveFilter sensitiveFilter;
    @Autowired
    public void setDiscussPostMapper(DiscussPostMapper discussPostMapper){
        this.discussPostMapper = discussPostMapper;
    }

    @Autowired
    public void setSensitiveFilter(SensitiveFilter sensitiveFilter) {
        this.sensitiveFilter = sensitiveFilter;
    }

    /*
        帖子总数缓存，LoadingCache是 Caffeine中的一个类，Caffeine是一个高性能的 Java 缓存库
         */
    private LoadingCache<Integer,Integer> postRowsCache;

    // 帖子列表缓存
    private LoadingCache<String,List<DiscussPost>> postListCache;

    /**
     * 初始化缓存数据
     */
    @PostConstruct
    public void initCache(){
        // 初始化帖子列表
        postListCache = Caffeine.newBuilder()
                // 最大限制个数
                .maximumSize(maxSize)
                // 写后过期
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(@NonNull String key) throws Exception {
                        if(key == null || key.length() == 0){
                            throw new IllegalArgumentException("参数错误");
                        }
                        String[] params = key.split(":");
                        if(params == null || params.length != 2){
                            throw new IllegalArgumentException("参数错误");
                        }
                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        // TODO：二级缓存 redis -> mysql
                        logger.debug("从数据库加载post");
                        return discussPostMapper.getDiscussPosts(0,offset,limit,1);
                    }
                });
        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds,TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {

                        // TODO :二级缓存 redis -> mysql
                        logger.debug("从数据库中加载post");
                        return discussPostMapper.getDiscussPostRows(key);
                    }
                });

    }

    /**
     * 查询指定用户的帖子数量，当userId = 0 时，表示查询所有帖子数量
     * @param userId
     * @return
     */
    @Override
    public int getDiscussPostRows(int userId) {
         // 首页查询走缓存(缓存是哪里放进去的)
        if(userId == 0){
            return postRowsCache.get(userId);
        }
        logger.debug("从数据库中加载帖子数量");
        return discussPostMapper.getDiscussPostRows(userId);
    }

    /**
     * 查询某个用户发送的帖子，当userId = 0 时，表示查询所有帖子
     * @param userId
     * @param offset
     * @param limit
     * @param orderMode orderMode 是首页的最热：1，最新：0
     * @return
     */
    @Override
    public List<DiscussPost> getDiscussPosts(int userId, int offset, int limit, int orderMode) {
        // 只有热门帖子（访问首页时，userId = 0）
        if(userId == 0 && orderMode == 1){
            return postListCache.get(offset + ":" + limit);
        }

        logger.debug("从数据库加载数据");
        return discussPostMapper.getDiscussPosts(userId,offset,limit,orderMode);
    }

    /**
     * 根据帖子id获取帖子详情
     * @param discussPostId
     * @return
     */
    @Override
    public DiscussPost getDiscussPostById(int discussPostId) {
        return discussPostMapper.getDiscussPostById(discussPostId);
    }

    /**
     * 更新帖子评论数量
     * @param id
     * @param commentCount
     * @return
     */
    @Override
    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id,commentCount);
    }

    /**
     * 发布帖子
     * @param post
     * @return
     */
    @Override
    public int addDiscussPost(DiscussPost post) {
        if(post == null){
            throw new IllegalArgumentException("参数不能为空");
        }

        // 转译为html标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        String content = HtmlUtils.htmlEscape(post.getContent());
        // 敏感词过滤
        post.setContent(sensitiveFilter.filter(content));
        return discussPostMapper.insertDiscussPost(post);
    }

    /**
     * 更新帖子状态
     * @param discussPostId
     * @param status
     * @return
     */
    @Override
    public int setPostStatus(int discussPostId, int status) {
       return discussPostMapper.updatePostStatus(discussPostId,status);
    }

    /**
     * 更改帖子状态
     * @param discussPostId
     * @param type
     * @return
     */
    @Override
    public int setPostType(int discussPostId, int type) {
        return discussPostMapper.updatePostType(discussPostId, type);
    }

    /**
     * 更新帖子分数
     * @param id
     * @param score
     * @return
     */
    @Override
    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }
}
